﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Graphs;
using System.Windows.Media;

namespace ConceptLink
{
    class SearchContext1Way : SearchContext
    {
        public List<Candidate> open = new List<Candidate>();
        public List<Article> closed = new List<Article>();


        public SearchContext1Way(Article from, Article to, Graph g) 
            : this(from, to)
        {

            Graph = g;

            Node n = new WikiVisNode()
            {
                text = From.title,
                fixedinplace = true,       
                id = from.id
            };

            Relatedness.TryGet(from.title, to.title, out (n as WikiVisNode).h);

            Graph.AddNode(n);
        }

        public SearchContext1Way(Article from, Article to)
        {
            this.From = from;
            this.To = to;

            open.Add(new Candidate() { article = From, destination = to, parent = null });         
          
        }
        protected SearchContext1Way()
        {
        }



        public override void Step(StepComplete callback)
        {
            /*
            if (Compelete)
            {
                callback(this);
                return;
            }
            */
            if (open.Count == 0)
            {
                Compelete = true;

                callback(this);
                return;
            }

            Iterations++;

            Candidate at = open.OrderBy(item => item.f).First();

            {
                List<Article> path = new List<Article>();

                for (var p = at; p != null; p = p.parent)
                    path.Add(p.article);

                path.Reverse();

                this.Path = path.ToArray();
            }


            closed.Add(at.article);
            open.Remove(at);



            Node node_at = null;
            Graph g = Graph;

            if (g != null)
            {
                node_at = g.GetNode(at.article.title);

                if (node_at == null)
                {
                    node_at = new WikiVisNode() { text = at.article.title, visible = true, id = at.article.id };
                    g.AddNode(node_at, g.GetNode(at.parent.article.title));

                    float rel = 0;
                    Relatedness.TryGet(at.article.title, at.parent.article.title, out rel);

                    (node_at as WikiVisNode).g = at.G;
                    (node_at as WikiVisNode).h = at.H;

                    Link l = g.AddLink(new WikiVisLink() { a = node_at, b = g.GetNode(at.parent.article.title), rel = rel });

                    l.AddArrowTo(node_at);

                    l.width = 10 * rel;
                }

                node_at.visible = true;

                if (at.parent != null)
                {
                    float rel = 0;
                    Relatedness.TryGet(at.article.title, at.parent.article.title, out rel);
                    Link l = g.AddLink(new WikiVisLink() { a = node_at, b = g.GetNode(at.parent.article.title), rel = rel });
                    l.visible = true;

                }

                Recolour();
            }

            if (at.article.title == To.title)
            {
                Compelete = true;
            }

            Links.Get(at.article.id, false, true, To.id,

            delegate(int idforget, Links.LinksResult[] outsresults, Links.LinksResult[] insresults)
            {
                int shown = 0;
           
                foreach (var link in outsresults.OrderBy(order =>
                {
                    float rel = 0;
                    Relatedness.TryGet(at.article.title, order.title, out rel);
                    return -rel;
                }))
                {
                    float rel = 0;
                    if (Relatedness.TryGet(at.article.title, link.title, out rel))
                    {

                        Node node_to = null;


                        node_to = g.GetNode(link.title);

                        if ((shown++ < 5) && (node_to == null))
                        {
                            node_to = new WikiVisNode() { text = link.title, visible = true, id = link.id };
                            g.AddNode(node_to, node_at);
                        }


                        if (node_to != null && ((rel >= 0.70) || (shown <= 5) || (node_to.text == To.title)))
                        {
                            Link l = g.AddLink(new WikiVisLink() { a = node_at, b = node_to, visible = false, rel = rel });

                            l.AddArrowTo(node_to);
                            //l.text = rel.ToString("0%");
                            l.width = 10 * rel;

                            l.visible = true;
                        }


                        if (closed.FirstOrDefault(item => item.id == link.id) == null)
                        {
                            Candidate existing = open.FirstOrDefault(item => item.article.id == link.id);

                            if (existing != null)
                            {
                                existing.UpdateParentIfBetter(at);
                            }
                            else
                            {
                                existing = new Candidate()
                                {
                                    article = link,
                                    parent = at
                                };
                                open.Add(existing);
                            }

                            if (g != null && node_to != null)
                            {
                                (node_to as WikiVisNode).g = existing.G;
                                (node_to as WikiVisNode).h = existing.H;
                            }
                        }
                    }
                }

                Recolour();

                callback(this);
            });
        }
                
        
        private void Recolour()
        {

            float maxg = 1;
            if (ColorFromStart)
            {
                maxg = 0;
                foreach (var n in Graph.GetNodes())
                {
                    float t = (n as WikiVisNode).g;

                    if (t > maxg)
                        maxg = t;
                }
                if (maxg == 0) maxg = 1;
            }

            var Light = HslColor.FromColor(Colors.Red) ;
                Light.L=.5 ;
            
            var Dark = HslColor.FromColor(Colors.Cyan);
            Dark.L = .5;


            foreach (var n in Graph.GetNodes())
            {
                float t = ColorFromStart ? (n as WikiVisNode).g : (n as WikiVisNode).h;
                float gg = t/ maxg;
                if (gg > 1) gg = 1;
                gg = gg * gg;
                n.color = new HslColor()
                {
                    A = 1,
                    H = (Light.H + (Dark.H - Light.H) * gg),
                    L = (Light.L + (Dark.L - Light.L) * gg),
                    S = (Light.S + (Dark.S - Light.S) * gg)
                }.ToColor(); ;
            }

            Color lc = Color.FromArgb(192, 79, 129, 189);

            foreach (var l in Graph.GetLinks())
            {
                l.color = lc;
                if (ShowTextOnLinks)
                {
                    l.text = (l as WikiVisLink).rel.ToString("0.0%");
                }
                else
                {
                    l.text = null;
                }
            }

            if (ColorCurrentPath)
            {
                for (int i = 0; i < Path.Length; i++)
                {
                    Graph.GetNode(Path[i].title).color = Colors.Orange;

                    if (i<Path.Length-1)
                        Graph.GetLink(Graph.GetNode(Path[i].title), Graph.GetNode(Path[i+1].title)).color = Colors.Orange;
                }
            }
        }


        public class Candidate
        {
            public Article article;
            public Article destination;

            public float G;
            public float H;
            public float f;

            public void Calc()
            {
                Relatedness.TryGet(article.title, destination.title, out H);
                
                H = 1 - H;
                
                if (H == 1)
                    H = 1000;


                f = G + H;
            }


            private Candidate _parent = null;

            public Candidate parent
            {
                set
                {
                    _parent = value;
                    if (value == null)
                    {
                        G = 0;
                    }
                    else
                    {
                        float h=0;
                        Relatedness.TryGet(article.title, _parent.article.title, out h);
                        G = _parent.G + 1 - h;
                        destination = parent.destination;
                    }
                    Calc();
                }
                get
                {
                    return _parent;
                }
            }

            internal void UpdateParentIfBetter(Candidate newparent)
            {
                if (_parent != null)
                {
                    float h = 0;
                    Relatedness.TryGet(article.title, newparent.article.title, out h);
                        
                    if (_parent.G + 1 - h < G)
                    {
                        parent = newparent;
                    }
                }
            }
        }
    }
}
